package cn.qingyun.gis.modules.school.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.qingyun.gis.modules.school.entity.dto.FuseCustomerChannelInfoDTO;
import cn.qingyun.gis.modules.school.entity.request.FuseCustomerChannelRequest;
import cn.qingyun.gis.modules.school.mapper.FuseCustomerChannelMapper;
import cn.qingyun.gis.modules.school.service.IK12SchoolsFuseCustomerChannelService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wanghui
 * @date 2024/1/11
 */
@Service
@Slf4j
public class K12SchoolsFuseCustomerChannelServiceImpl implements IK12SchoolsFuseCustomerChannelService {

    @Resource
    private FuseCustomerChannelMapper fuseCustomerChannelMapper;


    @Override
    public String getLastFuseTableName() {
        return fuseCustomerChannelMapper.getLastFuseTableName();
    }

    @Override
    public List<FuseCustomerChannelInfoDTO> queryFuseCustData(FuseCustomerChannelRequest request) {
        log.debug("K12SchoolsFuseCustomerChannelServiceImpl queryFuseCustData begin");
        // 处理请求
        request.setId(null);
        String keywords = request.getKeywords();
        if (ObjectUtil.isNotEmpty(keywords)) {
            // 匹配数字
            String regex = "^-?[1-9]\\d*$|^0$";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(keywords);
            if (matcher.matches()) {
                request.setId(Long.parseLong(keywords));
                request.setKeywords(null);
                log.debug("K12SchoolsFuseCustomerChannelServiceImpl queryFuseCustData begin request is id");
            }
        }

        // 查询表名
        String lastFuseTableName = fuseCustomerChannelMapper.getLastFuseTableName();
        // 查询数据
        IPage<FuseCustomerChannelInfoDTO> page = new Page<>(request.getPageNum(), request.getPageSize());

        request.setTableName(lastFuseTableName);
        List<FuseCustomerChannelInfoDTO> resultList = fuseCustomerChannelMapper.queryFuseCustData(page, request);
        if (log.isDebugEnabled()) {
            log.debug("K12SchoolsFuseCustomerChannelServiceImpl queryFuseCustData end  result is:{}", JSONUtil.toJsonStr(resultList));
        }
        return resultList;
    }
}
